<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :http-request="upload"
    :before-upload="beforeAvatarUpload"
  >
    <!-- 上传成功之后拿到地址回显头像 || 默认头像 -->
    <img v-if="photo" :src="photo" class="avatar" />
    <!-- 默认没有头像显示 + 号 -->
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    <!-- 显示上传进度 -->
    <el-progress
      v-show="showProcess"
      type="line"
      :percentage="percentage"
      status="success"
      :stroke-width="6"
    ></el-progress>
  </el-upload>
</template>

<script>
// 导入腾讯云cos接口插件
import COS from 'cos-js-sdk-v5'
//  初始化接口调用实例
const cos = new COS({
  // 秘钥ID
  SecretId: 'AKIDGLDV9cvwlLfmcNhGMYVL8g07zbc7vL6d',
  // 秘钥值
  SecretKey: 'YrFPM4VeZFeolUzOdx3MDMjYGmEAuPh7'
})
export default {
  name: 'UploadPhoto',
  props: {
    // 员工头像
    photo: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      // 是否显示进度条
      showProcess: false,
      // 进度条数值（0~100）
      percentage: 0
    }
  },
  methods: {
    upload (params) {
      console.log('进入自定义上传逻辑：', this, params)
      // 显示上传进度条
      this.showProcess = true
      // 执行上传方法
      cos.putObject({
        Bucket: 'hr-elem-1305861574',
        Region: 'ap-beijing',
        Key: params.file.name,
        StorageClass: 'STANDARD',
        Body: params.file,
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          // 获取上传进度,并存储=》
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        // err没有值表明上传成功
        if (!err) {
          console.log('上传返回的数据：', data, this)
          // 延迟显示进度条效果
          setTimeout(() => {
            //  回显上传成功的图片
            this.$emit('update:photo', `https://${data.Location}`)
            // 关闭进度条显示
            this.showProcess = false
          }, 800)
        }
      })
    },
    // 选择完图标之后校验
    beforeAvatarUpload (file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
